package com.anc.admin.model.admin.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 线程绑定变量类
 * <p>
 * 注意每个接口走到最后都要清除数据(目前是在aop拦截中执行的ThreadMapUtil.remove())
 *
 * @author caoyuan
 * @date 2021/4/30 下午 5:37
 * @since V1.0
 */
public class ThreadMapUtil {
    private static final ThreadLocal<Map<String, Object>> threadLocalMap = new ThreadLocal<>();

    private ThreadMapUtil() {

    }

    private static Map<String, Object> map() {
        Map<String, Object> map = threadLocalMap.get();
        if (map == null) {
            threadLocalMap.set(new HashMap<>());
            map = threadLocalMap.get();
        }
        return map;
    }

    public static void put(String key, Object value) {
        map().put(key, value);
    }

    public static <T> T get(String key) {
        return (T) map().get(key);
    }

    public static void remove(String key) {
        map().remove(key);
        if (map().isEmpty()) {
            threadLocalMap.remove();
        }
    }

    /**
     * 清除线程变量
     *
     * @return void
     * @author caoyuan
     * @date 2021/4/30 下午 5:43
     * @since V1.0
     */
    public static void remove() {
        threadLocalMap.remove();
    }

    //临时修改泛型,省去强转
    public static <T> T getOrDefault(String key, T defaultValue) {
        return (T) map().getOrDefault(key, defaultValue);
    }

    /**
     * 获取某个值，为空时创建mappingFunction
     *
     * @param key
     * @param mappingFunction
     * @return java.lang.Object
     * @author caoyuan
     * @date 2021/4/30 下午 5:43
     * @since V1.0
     */
    public static <T> T computeIfAbsent(String key, Function<? super String, ? extends T> mappingFunction) {
        return (T) map().computeIfAbsent(key, mappingFunction);
    }

    public static String getCurrentUserId() {
        return get("userId");
    }

    public static String getCurrentName() {
        return get("userName");
    }

    public static Long getCurrentCompanyId(){
        return get("companyId");
    }
}
